package com.springcloudalibaba.bclass.util;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * bean转化
 * @author lixing
 * @date 2020/12/24 0024 下午 2:20:35
 */
public class ConvertUtils {
    /**
     * @描述 将source实体类拷贝到targetClass类型的实体类并返回该实体类
     * @作者 lixing
     * @日期 2020/12/5 10:27
     * @Param [source, targetClass]
     * @return E
     */
    public static <T, E> E convert(T source, Class<E> targetClass) {
        E target = null;
        try {
            target = targetClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
        BeanUtils.copyProperties(source, target);
        return target;
    }

    /**
     * @描述 将sourceList集合拷贝到targetClass类型的集合并返回该集合
     * @作者 lixing
     * @日期 2020/12/5 10:27
     * @Param [source, targetClass]
     * @return E
     */
    public static <T, E> List<E> convertList(List<T> sourceList, Class<E> targetClass) {
        List<E> targetList = new ArrayList<>();
        for (T source : sourceList) {
            E target = convert(source, targetClass);
            targetList.add(target);
        }
        return targetList;
    }
}
